#!/bin/bash
APP_NAME=`cat .env|grep APP_NAME=|awk -F '=' '{print $2}'`
APP_ENV=`cat .env|grep APP_ENV=|awk -F '=' '{print $2}'`

function getPid(){
  pid=`ps -ef|grep $APP_NAME.Master|grep -v grep|awk '{print $1}'`
  echo $pid
}

function startCommand(){
  pid=`getPid`
  if [ $pid ]; then
    echo '启动失败：已存在正在运行的服务'
    exit
  fi
  if [[ $1 = '-q' ]];then
    message=`php bin/hyperf.php start`
  else
    php bin/hyperf.php start
  fi
}

function stopCommand(){
  pid=`getPid`
  if [ $pid ]; then
    kill -9 $pid
  fi
}

function optimizeCommand(){
  # 优化 Composer 索引
  composer dump-autoload -o
  # 生成代理类和注解缓存
  php bin/hyperf.php
}

function restartCommand(){
  if [[ $APP_ENV = 'prod' ]];then
    optimizeCommand
  fi
  stopCommand
  startCommand $1
}

function watchCommand(){
  pid=`getPid`
  if [ $pid ]; then
    echo '启动失败：已存在正在运行的服务'
    exit
  fi
  if [[ $APP_ENV = 'prod' ]];then
     echo '启动失败：生产环境下，禁止使用热更新'
     exit
   fi
  php bin/hyperf.php server:watch
}

function helpCommand(){
  cat <<END
  ----------------------------------------------------------------------------
  Usage:
    command [options]

  Example:
    ./server.sh start -q

  Options:
    -q  不输出信息

  Command:
    start     启动
    stop      关闭
    restart   重启
    watch     热更新
    optimize  优化索引（生产环境下，重启服务时会自动执行）
  ----------------------------------------------------------------------------
END
}

case $1 in
start)
  startCommand $2
  ;;
stop)
  stopCommand
  ;;
restart)
  restartCommand $2
  ;;
optimize)
  optimizeCommand
  ;;
watch)
  watchCommand
  ;;
*)
  helpCommand
  ;;
esac
